//
//  CommentViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/11/5.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class CommentViewController: BaseViewController {
    var tableview:UITableView!
    var tableDataSource:[CommentObj] = []
    var heightArray:NSMutableArray!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "更多评论"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.whiteColor()
        heightArray = NSMutableArray()
        self.createTableView()
        self.queryCommentsByID("22266")

        // Do any additional setup after loading the view.
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        tableview = UITableView(frame: CGRectMake(0, 64, view.bounds.size.width, view.bounds.size.height-64), style: UITableViewStyle.Plain)
        tableview.backgroundColor = UIColor.clearColor();
        tableview.separatorStyle = UITableViewCellSeparatorStyle.None
        tableview.showsHorizontalScrollIndicator = false
        tableview.showsVerticalScrollIndicator = false
        tableview.dataSource = self
        tableview.delegate = self
        tableview.registerClass(CommentCell.self, forCellReuseIdentifier:"CommentCellID")
//        tableview.header =  MJRefreshNormalHeader(refreshingBlock:{[weak self] in
//            self?.currentNumber = 0
//            self?.currentPage = 1
//            self?.queryOrderList(GlobalDataHelper.instance.session, orderstatus:self!.requestOrderType, offset: self!.currentPage, length: self!.length)
//            }
//        )
//        tableview.footer =  MJRefreshAutoNormalFooter(refreshingBlock:{[weak self] in
//            self?.currentPage++
//            self?.queryOrderList(GlobalDataHelper.instance.session, orderstatus:self!.requestOrderType, offset: self!.currentPage, length: self!.length)
//            }
//        )
//        tableview.footer.hidden = true
        view.addSubview(tableview)
    }
    func estimateCellHeight(){
        if self.tableDataSource.count == 0{
            return
        }
        for obj in self.tableDataSource{
            var aSize = CGSizeZero
            var height:CGFloat = 0.0
            if let content = obj.detail{
                let contentStr = content as NSString
                aSize = contentStr.sizewithFont(UIFont.systemFontOfSize(12), maxSize:CGSizeMake(view.bounds.size.width - 30, 200))
            }
            height = aSize.height+40.0
            self.heightArray.addObject(NSNumber(float: Float(height)))
        }
        
    }
    func queryCommentsByID(goodID:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(goodID, forKey: "id")
        request.requestStart("/pdp/listComment", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        if let array = dic?.pareseDataToCommentArray(){
                            self.tableDataSource = array
                            self.estimateCellHeight()
                            self.tableview.reloadData()
                        }
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        })
                    
                }
            }
        })
        self.showProcess("加载中...")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension CommentViewController:UITableViewDataSource,UITableViewDelegate{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return tableDataSource.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("CommentCellID", forIndexPath: indexPath) as! CommentCell
        let obj = tableDataSource[indexPath.row]
        cell.layoutWithData(obj)
//        cell.indexPath = indexPath
//        cell.name.text = "收货人："+obj.username!
//        cell.phone.text = obj.telephone
//        cell.address.text = obj.content
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        let height:Float = self.heightArray[indexPath.row].floatValue
        return  CGFloat(height)
    }
//    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
//        if indexPath.section == 0{
//            
//        }
//        else{
//            
//        }
//    }
}
